use std::collections::HashMap;
use log::info;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use crate::connection_manager::event::ConnectionEvent;
use crate::RpcResult;

/// 输出站，接受消息
pub struct OutputStation<E, C: ConnectionEvent> {
    pub data_map: HashMap<String, E>,
    pub stream_sender: UnboundedSender<C>,
}

pub trait OutputEvent<E: OutputEvent<E, C>, C: ConnectionEvent>: Send + Sync {
    fn handle(self, manager: &mut OutputStation<E, C>)-> RpcResult<()>;
}

impl <E: OutputEvent<E, C>, C: ConnectionEvent> OutputStation<E, C> {

    pub fn new(stream_sender: UnboundedSender<C>) -> OutputStation<E, C> {
        OutputStation {
            data_map: HashMap::new(),
            stream_sender,
        }
    }
    pub async fn run(mut self, mut receiver: UnboundedReceiver<E>) {
        while let Some(message) = receiver.recv().await {
            let result = message.handle(&mut self);
            if let Err(_e) = result {
                info!("Error handling stream message: {:?}", _e);
            }
        }
    }

}